package cn.spream.dream.service;

import cn.spream.dream.dao.user.UserDao;
import cn.spream.dream.domain.user.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;

/**
 * shiro 认证授权
 * Created with IntelliJ IDEA.
 * User: sjx
 * Date: 15-1-5
 * Time: 上午11:07
 * To change this template use File | Settings | File Templates.
 */
public class DreamAuthorizingRealm extends AuthorizingRealm {

    @Resource(name = "userDao")
    private UserDao userDao;

    /**
     * 授权信息
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;  //To change body of implemented methods use File | Settings | File Templates.
    }

    /**
     * 认证信息
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        String username = usernamePasswordToken.getUsername();
        User user = userDao.getByUsernameWithLogin(username);
        SimpleAuthenticationInfo simpleAuthenticationInfo = null;
        if (user != null) {
            simpleAuthenticationInfo = new SimpleAuthenticationInfo(user.getName(), user.getPassword(), getName());
        }
        return simpleAuthenticationInfo;
    }

}
